package com.softWang.file.service;

import com.softWang.common.base.BaseServiceMy;
import com.softWang.common.exception.LogicException;
import com.softWang.common.utils.SpringUtils;
import com.softWang.file.constants.FilesConstant;
import com.softWang.file.mapper.FileManageMapper;
import com.softWang.file.po.FileManage;
import com.softWang.file.util.IFileSaveUtil;
import com.softWang.file.util.MimeTypeUtils;
import com.softWang.file.vo.fileManage.FileManageQueryAllParam;
import com.softWang.file.vo.fileManage.FileManageQueryAllResult;
import com.softWang.file.vo.fileManage.FileSaveResult;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 文件表 服务实现类
 * </p>
 *
 * @author wang
 * @since 2025-05-06
 */
@Service
public class FileManageService extends BaseServiceMy<FileManage> {

     @Value("${file.fileSaveType}")
     private  String fileSaveType;
     @Resource
     private FileManageMapper fileManageMapper;

     /**
     * 分页条件查询
     * @param param
     * @return
     */
     public List<FileManageQueryAllResult> queryall(FileManageQueryAllParam param){
         param.startPage();
         List<FileManageQueryAllResult> results=fileManageMapper.queryall(param);
         return results;
     }

    public Map uploadFile(MultipartFile file,String subDir) throws Exception{
        IFileSaveUtil fileSaveUtil = SpringUtils.getBean(fileSaveType);
        subDir = subDir +"/" + extractFileDir(file);
        String fileName = extractFileSaveName(file);
        FileSaveResult fileSaveResult = fileSaveUtil.saveFile(file,subDir, fileName);

        FileManage baseFile = new FileManage();
        baseFile.setDeleted(0);
        baseFile.setCtime(LocalDateTime.now());
        baseFile.setFileDiskPath(subDir);
        baseFile.setFileSaveType(fileSaveType);
        baseFile.setFileType(getExtension(file));
        baseFile.setOriName(FilenameUtils.getName(file.getOriginalFilename()));
        baseFile.setFileUrl(fileSaveResult.getFileUrl());
        baseFile.setFileName(fileName);
        fileManageMapper.insert(baseFile);


        if(baseFile == null){
            throw new LogicException("保存文件失败");
        }
        Map map = new HashMap();
        map.put("fileId",baseFile.getFileId());
        map.put("oriName",baseFile.getOriName());
        return map;
    }

    public List<Map> uploadFiles(List<MultipartFile> files,String subDir) throws Exception{
        List<Map> fileList = new ArrayList<>();
        if(files != null && files.size() > 0){
            IFileSaveUtil fileSaveUtil = SpringUtils.getBean(fileSaveType);
            for (MultipartFile file : files) {
                Map map = new HashMap();
                subDir = subDir +"/" + extractFileDir(file);
                String fileName = extractFileSaveName(file);
                FileSaveResult fileSaveResult = fileSaveUtil.saveFile(file,subDir, fileName);

                FileManage baseFile = new FileManage();
                baseFile.setDeleted(0);
                baseFile.setCtime(LocalDateTime.now());
                baseFile.setFileDiskPath(subDir);
                baseFile.setFileSaveType(fileSaveType);
                baseFile.setFileType(getExtension(file));
                baseFile.setOriName(FilenameUtils.getName(file.getOriginalFilename()));
                baseFile.setFileUrl(fileSaveResult.getFileUrl());
                baseFile.setFileName(fileName);
                fileManageMapper.insert(baseFile);

                if(baseFile == null){
                    throw new LogicException("保存文件失败");
                }
                map.put("fileId",baseFile.getFileId());
                map.put("oriName",baseFile.getOriName());
                fileList.add(map);
            }
        }
        return fileList;
    }

    public Map getFileUrl(Long fileId) throws Exception {
        FileManage baseFile = fileManageMapper.selectById(fileId);
        Map map = new HashMap();
        if(baseFile != null && baseFile.getDeleted() == 0) {
            IFileSaveUtil fileSaveUtil = SpringUtils.getBean(baseFile.getFileSaveType());
            String fileUrl = fileSaveUtil.getFileUrl(baseFile);
            map.put("fileUrl",fileUrl);
        }else {
            map.put("fileUrl","");
        }
        return map;
    }

    public void deleteFile(Long fileId) throws Exception {
        FileManage baseFile = fileManageMapper.selectById(fileId);
        if(baseFile != null && baseFile.getDeleted() == 1) {
            return;
        }
        IFileSaveUtil fileSaveUtil = SpringUtils.getBean(baseFile.getFileSaveType());
        fileSaveUtil.deleteFile(baseFile);
        fileManageMapper.deleteById(fileId);
    }

    public void downFile(Long fileId, HttpServletResponse response) throws Exception {
        FileManage baseFile = fileManageMapper.selectById(fileId);
        if(baseFile == null){
            throw  new LogicException("文件不存在");
        }
        IFileSaveUtil fileSaveUtil = SpringUtils.getBean(baseFile.getFileSaveType());
        fileSaveUtil.downFile(baseFile,response);
    }

    /**
     * 编码文件名
     */
    private String extractFileDir(MultipartFile file)
    {
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
        return dateFormat.format(now);
    }

    private String extractFileSaveName(MultipartFile file)
    {
        String fileId = UUID.randomUUID().toString().replace("-", "");
        String extension = getExtension(file);
        return fileId + "." + extension;
    }

    private File getAbsoluteFile(String uploadDir, String fileName) throws IOException
    {
        File desc = new File(uploadDir + File.separator + fileName);
        if (!desc.exists())
        {
            if (!desc.getParentFile().exists())
            {
                desc.getParentFile().mkdirs();
            }
        }
        return desc;
    }

    /**
     * 获取文件名的后缀
     *
     * @param file 表单文件
     * @return 后缀名
     */
    private String getExtension(MultipartFile file)
    {
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        if (extension == null || extension.equals(""))
        {
            extension = MimeTypeUtils.getExtension(Objects.requireNonNull(file.getContentType()));
        }
        return extension;
    }
}
